<script setup>
  import * as math from 'mathjs';
  // import menuEdit from '@adm/base/menu/edit.vue';
  import { onMounted, reactive, ref, computed, watch, nextTick } from 'vue';
  // import useModalMinix from '@/hook/modal.js';
  // import { useUserStore } from "@/stores/user.js";
  // import { getList } from "@/api/api.js";
  // import { post } from '@/function/request/index.js'

  defineOptions({name: ''});
  // const {baseDataMap, formRef, form, saveForm, loading, submitLoading, closeModal} = useModalMinix();
  // const { baseURL } = useUserStore();
  const props = defineProps({})
  const emits = defineEmits(['on-ok']);
  // watch(() => foo, (newValue, oldValue) => {})
  const watermark = reactive({
    content: '[中国太平洋财产保险股份有限公司嘉兴中心支公司    199****7871]',
    width: 120,
    height: 64,
    image: '',
    font: {
      // color: 'rgba(225, 225, 225, 1)',
      color: 'rgba(0,0,0,1)', // 字体颜色
      fontSize: '16', // 字体大小
      fontWeight: 'bold', // 字重 normal
      fontFamily: 'Georgia', // 字体  sans-serif
      fontStyle: 'italic', // 字体样式 normal
      textAlign: 'left', // 文本对齐
      textBaseline: 'top', // 文本基线 hanging\alphabetic\middle\bottom\top
    },
    rotate: 40, // 水印的旋转角度，90至-90
    gap: [0, 0],// 水印之间的间距[水平, 垂直]
    zIndex: 9, // 水印元素的z-index值
  })
  const canvasWidth = ref(120);
  const canvasHeight = ref(60);
  const imgSrc = ref('')

  onMounted(() => {
    initCanvas();
  });
  
  const initCanvas = () => {
    const {rotate, width, height, font, content, gap, image} = watermark;
    const {color, fontSize, fontWeight, fontFamily, fontStyle, textAlign, textBaseline} = font;
    console.log(content);
    let _imgSrc = '', contentLen = 0, contentHeight = 0, radian = 0;
    // 计算旋转弧度，弧度 = (Math.PI/180) * 角度
    if(rotate) {
      radian = Math.abs(rotate) / 360 * 2 * Math.PI
    }
    if(content) {
      const tempDiv = document.getElementById('watermarkContent');
      // 水印文本长度（差异值20）
      contentLen = tempDiv.offsetWidth + 20;
      // 水印文本高度
      contentHeight = tempDiv.offsetHeight;

      // 创建水印 Canvas 对象实例
      const watermarkCanvas = document.createElement('canvas');
      // 放到body中
      document.body.appendChild(watermarkCanvas);
      // 初始化水印画布大小
      watermarkCanvas.width = contentLen;
      watermarkCanvas.height = contentHeight;
      // 水印 Canvas 对象上下文实例（动画动作绘图等都是在他的身上完成）
      const watermarkContext = watermarkCanvas.getContext("2d");
      // 设置填充文字样式
      watermarkContext.fillStyle = color;
      watermarkContext.textAlign = textAlign;
      watermarkContext.textBaseline = textBaseline;
      // normal bold 24px PingFang SC, PingFang SC-Medium
      watermarkContext.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
      // 居中显示水印
      watermarkContext.fillText(content, 0, 0);
      // 绘制
      watermarkContext.stroke();
      // 导出透明背景的图片
      const dataURL = watermarkCanvas.toDataURL('image/png', 1);
      _imgSrc = dataURL
      // 销毁水印 Canvas 节点
      watermarkCanvas.remove();
    }

    // 创建新 Canvas 对象实例，处理间隔以及旋转，图片水印
    const myCanvas = document.createElement('canvas');
    // 放到body中
    document.body.appendChild(myCanvas);
    // 新 Canvas 对象上下文实例（动画动作绘图等都是在他的身上完成）
    const myContext = myCanvas.getContext("2d");
    const watermarkImg = new Image()
    watermarkImg.src = _imgSrc || image;
    watermarkImg.onload = () => {
      if(rotate) { // 有角度，则需计算出水印倾斜后的实际宽高
        let mergeWeight = watermarkImg.height * math.sin(radian) + watermarkImg.width * math.cos(radian);
        let mergeHeight = watermarkImg.width * math.sin(radian) + watermarkImg.height * math.cos(radian);
        if(Math.abs(rotate) === 90) {
          mergeWeight = watermarkImg.height * 1 + watermarkImg.width * 0;
          mergeHeight = watermarkImg.width * 1 + watermarkImg.height * 0;
        }
        canvasWidth.value = myCanvas.width = mergeWeight + gap[0];
        canvasHeight.value = myCanvas.height = mergeHeight + gap[1];
        // 旋转是以画布的左上角为原点旋转的，先将原点平移到画布中心位置
        myContext.translate(mergeWeight / 2, mergeHeight / 2);
        myContext.rotate(rotate > 0 ? radian : -radian);
        // 水印是按照画布的中心点旋转的，画布的真实长宽也是按照水印的宽高以及旋转角度计算出来的
        // 所以此时水印的X轴绝对处于未添加间隔前画布的对角线上且原点处于画布的对角线的交点上
        // 故此只需要计算出来水印应该往X轴的反方向移动对少像素，以及向Y轴移动水印高的一半即可
        let dx = 0;
        if(Math.abs(rotate) > 45) {
          dx = -((mergeHeight / math.sin(radian)) / 2);
        } else {
          dx = -((mergeWeight / 2) / math.cos(radian));
        }
        if(Math.abs(rotate) === 90) { // 90°转换为弧度后计算出来的值会存在问题
          dx = -(mergeHeight / 2);
        }
        myContext.translate(dx, -watermarkImg.height / 2);
        // 间隙
        if(gap[0]) {
          let dy = math.sin(radian) * (gap[0] / 2);
          let dx = dy / math.tan(radian);
          myContext.translate(dx, rotate < 0 ? dy : -dy);
        }
        if(gap[1]) {
          let dy = math.cos(radian) * (gap[1] / 2);
          let dx = math.tan(radian) * dy;
          myContext.translate(rotate < 0 ? -dx : dx, dy);
        }
        // 绘制
        myContext.drawImage(watermarkImg, 0, 0);
      } else { // 无角度，则宽高只需要在原始水印加上对应的间隔即可
        canvasWidth.value = gap[0] + watermarkImg.width;
        canvasHeight.value = gap[1] + watermarkImg.height;
        console.log('canvasWidth', canvasWidth.value);
        console.log('canvasHeight', canvasHeight.value);
        myCanvas.width = canvasWidth.value;
        myCanvas.height = canvasHeight.value;
        // 绘制(居中显示)
        myContext.drawImage(watermarkImg, gap[0] / 2, gap[1] / 2);
      }
      // 导出透明背景的图片
      const myDataURL = myCanvas.toDataURL('image/png', 1);
      imgSrc.value = myDataURL;
      // 销毁 Canvas 节点
      myCanvas.remove();
    }
  }

  // 子组件暴露
  defineExpose({});

</script>

<template>
  <div style="display: flex;">
    <el-form ref="form" inline :model="watermark" :label-width="130" >
      <el-form-item label="水印角度" style="width: 100%;">
        <el-input-number :max="90" :min="-90" v-model="watermark.rotate" controls-position="right" @change="initCanvas" />
      </el-form-item>
      <el-form-item label="水印间隙（上下）" style="width: 100%;">
        <el-input-number :min="0" v-model="watermark.gap[0]" controls-position="right" @change="initCanvas" />
      </el-form-item>
      <el-form-item label="水印间隙（左右）" style="width: 100%;">
        <el-input-number :min="0" v-model="watermark.gap[1]" controls-position="right" @change="initCanvas" />
      </el-form-item>
    </el-form>
    <!-- <canvas class="myCanvas" id="myCanvas" :width="120" :height="64" :style="{zIndex: watermark.zIndex}"></canvas> -->
    <img :src="imgSrc" :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}" style="background-color: #f2f2f2;"/>

    <span id="watermarkContent" :style="{
      position: 'fixed',
      left: '-1000px',
      top: '-1000px',
      fontSize: watermark.font.fontSize + 'px',
      fontFamily: watermark.font.fontFamily,
      fontWeight: watermark.font.fontWeight,
      fontStyle: watermark.font.fontStyle,
    }">{{ watermark.content }}</span>
  </div>
</template>

<style lang="less" scoped>

</style>
